package com.wdd.myplatform.controller.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 * MQTT客户端工具类
 * @author wdd 2022/4/25
 */
@Slf4j
public class MqttClientUtil {
    public static void sendMqttMsg(String clientId, String topic, String content) {
        try {
            MqttMessage message = new MqttMessage(content.getBytes());
            message.setQos(2);
            MqttClient mqttClient = MqttClientManager.getMqttClientById(clientId);

            if (null == mqttClient) {
                log.error("Not exist mqttClient where it's clientId is {}", clientId);
                return;
            }

            mqttClient.publish(topic, message);
            log.info("Publish to mqtt broker,message={}", message);
        } catch (MqttException e) {
            log.error("MqttClient send msg faild!", e);
        }
    }
}
